//基础地址
import { useMemberStore } from '@/stores'

const baseURL = 'http://localhost:8080'
//添加拦截器
const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //拼接地址(非http开头的)
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    //请求超时
    options.timeout = 5000
    //添加小程序端请求标识
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    //添加token请求头表示
    const memberStore = useMemberStore()
    // const token = memberStore.profile?.token
    // if (token) {
    //   options.header.Authorization = token
    // }
    console.log(options)
    // console.log('token:', token)
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

//请求函数

//封装类型
interface Data<T> {
  code: string
  message: string
  data: T
}

// 返回Promise对象
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //请求成功
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 401 清理用户信息,退回到登录页
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          //标记为失败，不在进行后续操作
          reject(res)
        } else {
          //其他错误信息
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).message || '获取数值失败!!!',
          })
          reject(res)
        }
      },
      //请求失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误!!!!',
        })
      },
    })
  })
}
